﻿using System;
using System.Web;
using ThoughtWorks.QRCode.Codec;

namespace Als.Utils.Image
{
    public static class QRcodeHelper
    {

        #region 生成二维码图片

        /// <summary>
        /// 生成二维码图片
        /// QRcode qrCode = new QRcode();
        /// UserQrCode = qrCode.Create("http://www.masoft.cn" , 4, "/Content/Images/QrCode/");
        /// </summary>
        /// <param name="str">字符串</param>
        /// <param name="size">图片大小</param>
        /// <param name="path">图片位置 
        /// 例如  /Upload/qrcodeimages/
        /// </param>
        /// <returns>返回生成的二维码图片路径</returns>
        public static string Create(string str, int size, string path)
        {
            try
            {
                var qrCodeEncoder = new QRCodeEncoder
                {
                    QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE,//设置编码模式
                    QRCodeScale = size,//设置编码测量度
                    QRCodeVersion = 8,//设置编码版本
                    QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M//设置编码错误纠正
                };
                System.Drawing.Image image = qrCodeEncoder.Encode(str);
                var filename = "~" + path + Guid.NewGuid() + ".jpg";
                image.Save(HttpContext.Current.Request.MapPath(filename));
                return filename.Replace("~", "");
            }
            catch (Exception)
            {
                return "";
            }
        }

        #endregion




    }
}
